package com.doraro.platform.module.user.controller;


import com.doraro.platform.common.beans.params.ValidateGroups;
import com.doraro.platform.common.exception.ApiGlobalException;
import com.doraro.platform.common.utils.HttpContextUtils;
import com.doraro.platform.common.utils.JwtUtil;
import com.doraro.platform.common.utils.Result;
import com.doraro.platform.common.utils.ShiroUserUtil;
import com.doraro.platform.module.user.model.dto.UserDetail;
import com.doraro.platform.module.user.model.entity.SysRole;
import com.doraro.platform.module.user.model.entity.SysUser;
import com.doraro.platform.module.user.model.vo.SysUserParam;
import com.doraro.platform.module.user.service.ICatchaService;
import com.doraro.platform.module.user.service.ISysRoleService;
import com.doraro.platform.module.user.service.ISysUserService;
import com.yufeixuan.captcha.Captcha;
import com.yufeixuan.captcha.GifCaptcha;
import com.yufeixuan.captcha.utils.CaptchaUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author doraroAllow-Origin
 * @since 2019-04-21
 */
@RestController
@RequestMapping("/api/user")
@Api(description = "用户相关接口", tags = "user")
public class SysUserRestController {
    private final ISysUserService userService;
    private ICatchaService captchaService;
    private final ISysRoleService roleService;
    @Autowired
    public SysUserRestController(ISysUserService userService, ICatchaService captchaService, ISysRoleService roleService) {
        this.userService = userService;
        this.captchaService = captchaService;
        this.roleService = roleService;
    }

    @GetMapping(value = "/info")
    @ApiOperation("获得用户详细信息")
    public Result getUserInfo(HttpServletRequest request) {
        final String jwt = HttpContextUtils.getJWT(request);
        final String userId = JwtUtil.getUserId(jwt);
        if (!JwtUtil.verify(jwt, userId)) {
            throw new ApiGlobalException("jwt不合法");
        }
        UserDetail userDetail = userService.getUserDetail(userId);
        return new Result().ok().addData("user", userDetail);
    }
    @ApiOperation("登录并获取jwt token")
    @PostMapping("/login")
    public Result login(@Validated(SysUserParam.Login.class) @RequestBody SysUserParam user, HttpServletRequest request) {
        boolean capCheck = captchaService.checkCaptcha(user.getUuid(), user.getCaptcha());
        if (!capCheck) {
            return new Result().error(HttpStatus.BAD_REQUEST, "验证码错误");
        }
        final SysUser sysUser = userService.login(user, request);
        return new Result().ok().addData("token", JwtUtil.toToken(sysUser.getId()));
    }

    @GetMapping(value = "captcha.jpg", produces = MediaType.IMAGE_JPEG_VALUE)
    @ApiOperation("获得验证码")
    public void captcha(HttpServletResponse response, @RequestParam String uuid) throws IOException {
        CaptchaUtil.setHeader(response, 1);
        GifCaptcha gifCaptcha = new GifCaptcha(130, 48, 5);
        gifCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
        captchaService.saveCaptcha(uuid, gifCaptcha.text().toLowerCase());
        gifCaptcha.out(response.getOutputStream());
    }

    @PostMapping("/register")
    @ApiOperation("注册账号")
    public Result register(@Validated(ValidateGroups.Create.class) @RequestBody SysUserParam param) {
        boolean capCheck = captchaService.checkCaptcha(param.getUuid(), param.getCaptcha());
        if (!capCheck) {
            return new Result().error(HttpStatus.BAD_REQUEST, "验证码错误");
        }
        userService.register(param);
        return new Result().ok();
    }

    @GetMapping("/roles")
    @ApiOperation("获取全部可注册的角色列表")
    public Result getByAllRole() {
        final List<SysRole> roles = roleService.getPublicRoles();
        return new Result().ok().addData("roles", roles);
    }

    @PostMapping("/logout")
    @ApiOperation("登出账号")
    public Result logout() {
        ShiroUserUtil.cleanCache();
        return new Result().ok();
    }
}

